package com.youjiang.springboot.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.youjiang.springboot.mapper.UserMapper;
import com.youjiang.springboot.service.UserService;

/**
 * Description: 用户操作控制器
 * Company: youjiang
 * @author Kwum
 * @date 2017年4月21日 上午9:30:58
 * @version 1.0
 */
@RestController
@RequestMapping(value = "springboot", produces="application/json;charset=UTF-8")
public class UserController {

	@Resource
	private UserService userService;
	@Resource
	private UserMapper userMapper;
	
	/**
	 * 根据状态查看用户列表
	 * @param state 状态码：1正常、0不显示
	 * @param currentPage 当前页码
	 * @param totalCount 当前页需要的条目数
	 * @return json数据，包含用户id、昵称、创建时间、更新时间、状态
	 * @throws Exception
	 * @author kwum
	 */
	@GetMapping("users")
	public String showUserList(
			@RequestParam(value="state", required=false, defaultValue="1")int state,
			@RequestParam(value="currentPage", required=false, defaultValue="1")int currentPage,
			@RequestParam(value="totalCount", required=false, defaultValue="10")int totalCount) throws Exception{
		
		return userService.selectUserPageDataByState(state, currentPage, totalCount).toString();
	}
	
	/**
	 * 根据id查看用户详情
	 * @param userId
	 * @return json数据，包含用户id、昵称、创建时间、更新时间、状态
	 * @throws Exception
	 * @author kwum
	 */
	@GetMapping("user/{id}")
	public String showUserInfo(
			@PathVariable(value = "id")int userId) throws Exception{
		
		return userService.montageUserInfoData(userMapper.selectByPrimaryKey(userId)).toString();
	}
	
	/**
	 * 新增用户
	 * @param nick 昵称
	 * @return json数据
	 * @throws Exception
	 * @author kwum
	 */
	@PostMapping("user")
	public String insertUser(
			@RequestParam(value="nick", required=true)String nick) throws Exception{
		
		return userService.addUser(nick).toString();
	}
	
	/**
	 * 更新用户
	 * @param userId 用户id
	 * @param state 状态码：1正常、0删除、-99不修改，可不传，默认-99
	 * @param nick 昵称，可不传，默认空
	 * @return json数据
	 * @throws Exception
	 * @author kwum
	 */
	@PutMapping("user")
	public String updateUser(
			@RequestParam(value="userId", required=true)int userId,
			@RequestParam(value="state", required=false, defaultValue="-99")int state,
			@RequestParam(value="nick", required=false, defaultValue="")String nick) throws Exception{
		
		return userService.updateUser(userId, state, nick).toString();
	}
}
